class_name VelocityBasedRotation
extends Node

# ===============================================

@export var enabled: bool = true :
	set(value):
		enabled = value
		if not enabled and target:
			target.rotation = 0.0

@export var target: Node2D
@export var max_rotation_degrees: int = 30
@export var x_velocity_threshold: float = 3.0
@export_range(0.25, 1.5) var lerp_seconds: float = 0.4

# ===============================================

var angle: float
var progress: float
var time_elapsed: float = 0.0
var velocity: Vector2
var last_position: Vector2

# ===============================================

# 固定帧率执行
func _physics_process(delta: float) -> void:
	if not enabled or not target:
		return
	velocity = target.global_position - last_position
	last_position = target.global_position
	progress = time_elapsed / lerp_seconds
	
	if abs(velocity.x) > x_velocity_threshold:
		angle = velocity.normalized().x * deg_to_rad(max_rotation_degrees)
	else:
		angle = 0.0
	
	target.rotation = lerp_angle(target.rotation, angle, progress)
	time_elapsed += delta
	
	if progress > 1.0:
		time_elapsed = 0.0
